package com.example.photongrid;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

public class JoinGame extends Activity {
	
	String string, ip = null;
	Socket socket;
	  ObjectInputStream in;
	  ObjectOutputStream out;
	
	protected void onCreate(Bundle savedInstanceState) {
		
		

		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.joingame);
		//Button b1 =(Button)findViewById(R.id.b3);
		//b1.setOnClickListener(buttonhandler2);
		
		new JoinGameTask().execute();
		//new StartClientThreadTask().execute();
		
		final Button refreshButton = (Button) findViewById(R.id.b3);
	    refreshButton.setOnClickListener(new View.OnClickListener() {
	      public void onClick(View view) {
	    	  TextView tv = (TextView) findViewById(R.id.ServerIP);
			tv.setText(ip);
	    }
	    });
	    
	    final Button startGameButton = (Button) findViewById(R.id.clientStartButton);
	    startGameButton.setOnClickListener(new View.OnClickListener() {
	      public void onClick(View view) {
	    	  Intent myIntent = new Intent(getApplicationContext(), HarnessClient.class);
				startActivity(myIntent);
	    	  
	    	  
	    }
	    });
		
		
		

	}
	
	private class JoinGameTask extends AsyncTask<Void, String, String> {
	    protected void onPostExecute(String result) {
	    }

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			try {
				String str;
				HttpClient httpclient = new DefaultHttpClient();
	            HttpGet httpget = new HttpGet("http://ip2country.sourceforge.net/ip2c.php?format=JSON");
	            HttpResponse response;
	            response = httpclient.execute(httpget);
	            HttpEntity entity = response.getEntity();
	            entity.getContentLength();
	            str = EntityUtils.toString(entity);
	            try {
	            	JSONObject obj =  (new JSONObject(str));
	                str = obj.getString("ip");
	            } 
	            catch (JSONException e) {
	            	e.printStackTrace();
	            }
	            string = str;
			    Log.i("IP", string);
			    
			    //tell DB that I am creating a game and get an assigned ID number
				try 
				{
						DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
						Connection conn = DriverManager.getConnection("jdbc:oracle:thin:hr/hr@oracle1.cise.ufl.edu:1521:orcl", "s93022ai", "adt2913*");  // don't go hacking my account Nuri :P lol
						
						Statement stmt = conn.createStatement();
						
						String query = "select HOSTIP from HOSTEDGAMES"; 
						ResultSet results = stmt.executeQuery(query);
						results.next();
						ip = results.getString("HOSTIP");
						 
						query = "update HOSTEDGAMES set PLAYER1 = '" + string + "' where HOSTIP = '" + ip + "'";
						stmt.executeQuery(query);
						conn.close();	
						
				} 
				catch (SQLException e) 
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			    
			} 
			catch (MalformedURLException e) {
				e.printStackTrace();
			}
		    catch (IOException e) {
		        e.printStackTrace();
		    }
			return null;
		}

	
	}
	
	private class StartClientThreadTask extends AsyncTask<Void, String, String> {
	    protected void onPostExecute(String result) {
	    }

		@Override
		protected String doInBackground(Void... params) {
			
			/*while(ip == null)
			{
				
			}*/
						return null;
		}

	
	}
}






